package jmu.edu.yjc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.JsonObject;
import jmu.edu.yjc.Utils.BeanCopyUtil;
import jmu.edu.yjc.constants.SystemConstants;
import jmu.edu.yjc.domain.ResponseResult;
import jmu.edu.yjc.domain.bo.MessageBo;
import jmu.edu.yjc.domain.entity.Message;
import jmu.edu.yjc.domain.entity.User;
import jmu.edu.yjc.domain.vo.PageVo;
import jmu.edu.yjc.domain.vo.message.UnreadVo;
import jmu.edu.yjc.domain.vo.user.UserContactVo;
import jmu.edu.yjc.domain.vo.user.UserVo;
import jmu.edu.yjc.mapper.MessageMapper;
import jmu.edu.yjc.mapper.UserMapper;
import jmu.edu.yjc.service.MessageService;
import jmu.edu.yjc.service.UpLoadService;
import jmu.edu.yjc.service.WebSocketService;
import jmu.edu.yjc.service.user.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Service("webSocketService")
public class WebSocketServiceImpl implements WebSocketService {
    @Resource
    private UserService userService;
    @Resource
    private MessageService messageService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UpLoadService upLoadService;
    /**
     * websocket open 时返回所有的服务人员
     * 给用户
     * @param id
     * @return
     *
     */
    @Override
    public ResponseResult getContacts(Long id) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.ge(User::getType,1);
        List<User> users = userService.list(wrapper);
        List<UserContactVo> userContactVos = new ArrayList<>();
        Map<Long,UnreadVo> unreadMap = messageService.getUnreadList(id);
        for (User user : users) {
            UserContactVo userContactVo = new UserContactVo();
            userContactVo.setId(user.getId());
            userContactVo.setAvatar(user.getAvatar());
            userContactVo.setDisplayName(user.getNickName());
            if(unreadMap.get(user.getId()) != null ){
                userContactVo.setUnread(unreadMap.get(user.getId()).getUnread());
            } else {
                userContactVo.setUnread(0);
            }
            Message message = messageService.getLassMessageById(id, user.getId());
            if(message != null) {
                userContactVo.setType(message.getType());
                userContactVo.setLastContent(message.getMessage());
                userContactVo.setLastSendTime(message.getCreateTime());
            }
            userContactVos.add(userContactVo);
        }
        return ResponseResult.okResult(userContactVos);
    }

    /**
     * 分页查询
     * 查询消息记录
     * @param pageNumber
     * @param userId
     * @param toUserId
     * @return
     */
    @Override
    public ResponseResult getMessages(Integer pageNumber,Integer pageSize, Long userId, Long toUserId) {
        PageVo pageVo = null;
        if(toUserId == 4){
            List<MessageBo> messages = new ArrayList<>();
            MessageBo messageBo = new MessageBo();
            messageBo.setFromUserId(toUserId);
            messageBo.setToUserId(userId);
            messageBo.setType("text");
            messageBo.setId(new Date().getTime());
            messageBo.setMessageStatus("0");
            messageBo.setCreateTime(new Date());
            messageBo.setMessage("你好我是机器人小C我可以回答你的一些关于医疗疾病的问题\n" +
                    "为了您的隐私我们本次会话的内容将不会被保存您可以尝试这么问我：\n" +
                    "1.腹痛的原因是什么\n" +
                    "2.腹痛应该吃什么药\n" +
                    "3.腹痛应该吃什么东西\n" +
                    "4.腹痛不能吃什么东西\n" +
                    "5.腹痛需要做什么检查\n" +
                    "6.什么人更容易腹痛\n" +
                    "7.得了什么病不能吃冰淇淋\n" +
                    "等等。。。\n" +
                    "您所问的问题应是关于医疗的问句，不同的问题请以英文逗号分隔开，\n" +
                    "否则可能得不到正确答案！本系统暂不具备上下文推断功能");
            User user = userService.getById(toUserId);
            UserVo userVo = BeanCopyUtil.copyBeans(user, UserVo.class);
            messageBo.setUser(userVo);
            messages.add(messageBo);
            Long total = 1L;
            pageVo = new PageVo(messages,total);
        }else {
            pageVo = messageService.getMessages(pageNumber,pageSize ,userId, toUserId);
        }
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getTotalUnRead(Long id) {
        Integer totalUnread = messageService.getTotalUnread(id);
        return ResponseResult.okResult(totalUnread);
    }

    @Override
    public ResponseResult updateMessagesByUserId(Long fromUserId,Long toUserId) {
        LambdaUpdateWrapper<Message> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Message::getFromUserId,fromUserId);
        wrapper.eq(Message::getToUserId,toUserId);
        wrapper.eq(Message::getIsCheck, SystemConstants.MESSAGE_UNREAD);
        wrapper.set(Message::getIsCheck,SystemConstants.MESSAGE_READ);
        messageService.update(null,wrapper);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getToUserContracts(Long id) {
        List<UserContactVo> contacts = new ArrayList<>();
        User robot = userService.getRobot();
        UserContactVo vo = new UserContactVo();
        vo.setId(robot.getId());
        vo.setDisplayName(robot.getNickName());
        vo.setAvatar(robot.getAvatar());
        vo.setLastSendTime(new Date());
        vo.setLastContent(" ");
        vo.setType("text");
        vo.setUnread(0);
        contacts.add(vo);
        contacts.addAll(userMapper.getContracts(id));
        for (UserContactVo contact : contacts) {
            contact.setUnread(messageService.getUnread(contact.getId(),id));
        }
        return ResponseResult.okResult(contacts);
    }

    @Override
    public ResponseResult updateMessageById(String messageId) {
        LambdaUpdateWrapper<Message> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Message::getIsCheck,SystemConstants.MESSAGE_READ);
        wrapper.eq(Message::getMessageId,messageId);
        messageService.update(wrapper);
        return ResponseResult.okResult();
    }
    @Transactional
    @Override
    public ResponseResult uploadFile(MultipartFile multipartFile, String message) {
        ResponseResult result = null;
        try {
            result = upLoadService.uploadFile(multipartFile);
            HashMap map = JSONObject.parseObject(message,HashMap.class);
            map.put("content",result.getData());
            messageService.addMessage(JSONObject.toJSONString(map));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
